package com.jfire.socket.socketserver.util;

import java.nio.ByteBuffer;
import com.jfire.socket.socketserver.exception.LessThanProtocolException;
import com.jfire.socket.socketserver.exception.NotFitProtocolException;
import com.jfire.socket.socketserver.exception.NotIntactDataException;

public class CheckReadBuffer
{
    /**
     * 对buffer从posi开始的11个字节进行检查，如果检查通过，返回报文体的长度。否则抛出异常。
     * 检查不会对buffer的位置信息等造成改变
     * 
     * @param buffer
     * @param headFactory
     * @return
     * @throws LessThanProtocolException
     * @throws NotFitProtocolException
     * @throws NotIntactDataException
     * @author windfire(windfire@zailanghua.com)
     */
    public static int checkReadBuffer(ByteBuffer buffer, HeadFactory headFactory) throws LessThanProtocolException, NotFitProtocolException, NotIntactDataException
    {
        int posi = buffer.position();
        if (buffer.remaining() < 11)
        {
            throw new LessThanProtocolException();
        }
        if (headFactory.fitHeadPtotocol(buffer, posi) == false)
        {
            throw new NotFitProtocolException();
        }
        int length = buffer.getInt(posi + 7);
        if (length > buffer.remaining() - 11)
        {
            throw new NotIntactDataException(length);
        }
        return length;
    }
}
